#include <iostream>
#include <sys/socket.h>
#include <string>
#include <arpa/inet.h>
#include <netinet/in.h>
#include"Tcp_server.hpp"

using namespace std;

void Useage(const string& proc)
{
    cout << "\n\rUseage:" << proc << "serverip serverproc" << endl;
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Useage(argv[0]);
        exit(0);
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    while(true)
    {
        int cnt = 5;
        bool isreconnect = false;
        int sockfd = 0;
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if(sockfd < 0)
        {
            cerr << "socket error" << endl;
            return 1;
        }
        do 
        {
            int n = connect(sockfd, (const struct sockaddr *)&server, sizeof(server));
            if(n < 0)
            {
                isreconnect = true;
                cnt--;
                cerr << "connect error..., reconnect: " << cnt << endl;
                sleep(2);
            }
            else
            {
                break;
            }
        }while(cnt && isreconnect);

        if(cnt == 0)
        {
            cerr << "user offline..." << endl;
            break;
        }

        string message;
        cout << "please Enter#";
        getline(cin, message);

        int n = write(sockfd, message.c_str(), message.size());
        if(n < 0)
        {
            cerr << "write error..." << endl;
        }

        char inbuffer[4096];
        n = read(sockfd, inbuffer, sizeof(inbuffer));
        if(n > 0)
        {
            inbuffer[n] = 0;
            cout << inbuffer << endl;
        }
        else
        {
            break;
        }
        close(sockfd);
    }

    return 0;
}